#!/bin/sh

. /usr/share/common

start() {
	echo_title "Starting NTP daemon"

	if [ "true" = "$wlanap_enabled" ]; then
		touch "$NTP_WORKING_FILE"
		DAEMON_ARGS="-n -l"
	else
		DAEMON_ARGS="-n -S /etc/ntpd_callback"
	fi

	if [ -f "$NTP_WORKING_FILE" ]; then
		echo_info "working configuration found"
	else
		if [ -f "$NTP_DEFAULT_FILE" ]; then
			echo_info "default configuration found"
		else
			echo_info "restore default config from ROM"
			cp "/rom$NTP_DEFAULT_FILE" "$NTP_DEFAULT_FILE"
		fi

		echo_info "use default configuration"
		cp "$NTP_DEFAULT_FILE" "$NTP_WORKING_FILE"
	fi

	start_daemon

	if [ "true" = "$wlanap_enabled" ]; then
		echo_info "WLAN AP mode. Skip sync time"
	elif [ -f /run/portal_mode ]; then
		echo_info "Portal mode. Skip sync time"
	else
		echo_info "Sync time"
		ntpd -q -N &
	fi
}

stop() {
	echo_title "Stopping NTP daemon"

	stop_daemon
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		sleep 1
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
